package com.xnet.shiro.manager.base.impl;

import com.xnet.common.constant.SystemConstant;
import com.xnet.common.constant.SystemConstant.StatusType;
import com.xnet.common.entity.Page;
import com.xnet.common.entity.Query;
import com.xnet.common.entity.UserEntity;
import com.xnet.common.utils.ShiroUtils;
import com.xnet.shiro.entity.base.UserRelationEntity;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.xnet.shiro.dao.authorize.ModuleMapper;
import com.xnet.shiro.dao.base.RoleMapper;
import com.xnet.shiro.dao.base.UserMapper;
import com.xnet.shiro.dao.base.UserRelationMapper;
import com.xnet.shiro.manager.base.UserManager;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * 系统用户
 *
 * @author Xingyc
 * @date 2018-1-8 17:57:53
 */
@Component("sysUserManager")
public class UserManagerImpl implements UserManager {

	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private ModuleMapper moduleMapper;
	
	@Autowired
	private RoleMapper roleMapper;
	
	@Autowired
	private UserRelationMapper userRelationMapper;
	
	
	@Override
	public List<UserEntity> listUser(Page<UserEntity> page, Query search) {
		return userMapper.listForPage(page, search);
	}

	@Override
	public UserEntity getByUserName(String username) {
		return userMapper.getByUserName(username);
	}

	@Override
	@Transactional
	public int saveUser(UserEntity userEntity) {
		String userId=userEntity.getUserId();
		int count = userMapper.save(userEntity);
		String roleId=userEntity.getRoleId();
		String logUserId=ShiroUtils.getUserId();
		String logUserName=ShiroUtils.getUserEntity().getAccount();
		userRelationMapper.removeByUserId(userId,1);

		if(!StringUtils.isBlank(roleId))
		{
			UserRelationEntity userRelationEntity=new UserRelationEntity();
			userRelationEntity.setUserRelationId(UUID.randomUUID().toString());
			userRelationEntity.setCategory(SystemConstant.AuthorizeCategoryEnum.Role.getValue());
			userRelationEntity.setIsDefault(1);
			userRelationEntity.setUserId(userId);
			userRelationEntity.setObjectId(roleId);
			userRelationEntity.setCreateDate(new Date());
			userRelationEntity.setCreateUserId(logUserId);
			userRelationEntity.setCreateUserName(logUserName);
			userRelationEntity.setSortCode(1);
			userRelationMapper.save(userRelationEntity);
		}

		String postId=userEntity.getPostId();
		if(!StringUtils.isBlank(postId))
		{
			UserRelationEntity userRelationEntity=new UserRelationEntity();
			userRelationEntity.setCategory(SystemConstant.AuthorizeCategoryEnum.Post.getValue());
			userRelationEntity.setIsDefault(1);
			userRelationEntity.setUserId(userId);
			userRelationEntity.setObjectId(postId);
			userRelationEntity.setCreateDate(new Date());
			userRelationEntity.setCreateUserId(logUserId);
			userRelationEntity.setCreateUserName(logUserName);
			userRelationEntity.setSortCode(1);
			userRelationMapper.save(userRelationEntity);
		}

		String jobId=userEntity.getPostId();
		if(!StringUtils.isBlank(postId))
		{
			UserRelationEntity userRelationEntity=new UserRelationEntity();
			userRelationEntity.setCategory(SystemConstant.AuthorizeCategoryEnum.Job.getValue());
			userRelationEntity.setIsDefault(1);
			userRelationEntity.setUserId(userId);
			userRelationEntity.setObjectId(jobId);
			userRelationEntity.setCreateDate(new Date());
			userRelationEntity.setCreateUserId(logUserId);
			userRelationEntity.setCreateUserName(logUserName);
			userRelationEntity.setSortCode(1);
			userRelationMapper.save(userRelationEntity);
		}




//		Query query = new Query();
//		query.put("userId", userEntity.getUserId());
//		query.put("roleIdList", userEntity.getRoleIdList());
//		userRelationMapper.save(query);
		return 1;
	}

	@Override
	public UserEntity getById(String userId) {
		UserEntity user = userMapper.getObjectById(userId);
    	//user.setRoleIdList(userRelationMapper.listUserRoleId(userId));
		return user;
	}

	@Override
	public int updateUser(UserEntity userEntity) {
		int count = userMapper.update(userEntity);
 	    String userId =userEntity.getUserId();
		String roleId=userEntity.getRoleId();
		String logUserId=ShiroUtils.getUserId();
		String logUserName=ShiroUtils.getUserEntity().getAccount();
		userRelationMapper.removeByUserId(userId,1);

		if(!StringUtils.isBlank(roleId))
		{
			UserRelationEntity userRelationEntity=new UserRelationEntity();
			userRelationEntity.setUserRelationId(UUID.randomUUID().toString());
			userRelationEntity.setCategory(SystemConstant.AuthorizeCategoryEnum.Role.getValue());
			userRelationEntity.setIsDefault(1);
			userRelationEntity.setUserId(userId);
			userRelationEntity.setObjectId(roleId);
			userRelationEntity.setCreateDate(new Date());
			userRelationEntity.setCreateUserId(logUserId);
			userRelationEntity.setCreateUserName(logUserName);
			userRelationEntity.setSortCode(1);
			userRelationMapper.save(userRelationEntity);
		}

		String postId=userEntity.getPostId();
		if(!StringUtils.isBlank(postId))
		{
			UserRelationEntity userRelationEntity=new UserRelationEntity();
			userRelationEntity.setUserRelationId(UUID.randomUUID().toString());
			userRelationEntity.setCategory(SystemConstant.AuthorizeCategoryEnum.Post.getValue());
			userRelationEntity.setIsDefault(1);
			userRelationEntity.setUserId(userId);
			userRelationEntity.setObjectId(postId);
			userRelationEntity.setCreateDate(new Date());
			userRelationEntity.setCreateUserId(logUserId);
			userRelationEntity.setCreateUserName(logUserName);
			userRelationEntity.setSortCode(1);
			userRelationMapper.save(userRelationEntity);
		}

		String jobId=userEntity.getPostId();
		if(!StringUtils.isBlank(postId))
		{
			UserRelationEntity userRelationEntity=new UserRelationEntity();
			userRelationEntity.setUserRelationId(UUID.randomUUID().toString());
			userRelationEntity.setCategory(SystemConstant.AuthorizeCategoryEnum.Job.getValue());
			userRelationEntity.setIsDefault(1);
			userRelationEntity.setUserId(userId);
			userRelationEntity.setObjectId(jobId);
			userRelationEntity.setCreateDate(new Date());
			userRelationEntity.setCreateUserId(logUserId);
			userRelationEntity.setCreateUserName(logUserName);
			userRelationEntity.setSortCode(1);
			userRelationMapper.save(userRelationEntity);
		}
//		userRelationMapper.remove(userId);
//		Query query = new Query();
//		query.put("userId", userId);
//		query.put("roleIdList", user.getRoleIdList());
//		userRelationMapper.save(query);
		return count;
	}

	@Override
	public int batchRemove(String[] id) {
		int count = userMapper.batchRemove(id);
		userRelationMapper.batchRemoveByUserId(id);
		return count;
	}

	@Override
	public Set<String> listUserPerms(String userId) {
		List<String> perms = moduleMapper.listUserPerms(userId);
		Set<String> permsSet = new HashSet<>();
		for(String perm : perms) {
			if(StringUtils.isNotBlank(perm)) {
				permsSet.addAll(Arrays.asList(perm.trim().split(",")));
			}
		}
		return permsSet;
	}

	@Override
	public Set<String> listUserRoles(String userId) {
		List<String> roles = roleMapper.listUserRoles(userId);
		Set<String> rolesSet = new HashSet<>();
		for(String role : roles) {
			if(StringUtils.isNotBlank(role)) {
				rolesSet.addAll(Arrays.asList(role.trim().split(",")));
			}
		}
		return rolesSet;
	}

	@Override
	public int updatePswdByUser(Query query) {
		return userMapper.updatePswdByUser(query);
	}

	@Override
	public int updateUserEnable(String[] ids) {
		return updateUserStatus(ids,StatusType.ENABLE.getValue());
	}

	@Override
	public int updateUserDisable(String[] ids) {
		return updateUserStatus(ids,StatusType.DISABLE.getValue());
	}

	/**
	 * 更新用户状态值
	 * @param statusType
	 */
	private int updateUserStatus(String[] ids,int statusType)
	{
		Query query = new Query();
		query.put("enabledMark", statusType);
		query.put("userIds", ids);
		int count = userMapper.updateUserStatus(query);
		return count;

	}

	@Override
	public int updatePswd(UserEntity user) {
		return userMapper.updatePswd(user);
	}

	@Override
	public UserEntity getUserById(String userId) {//不包含角色信息
		return userMapper.getObjectById(userId);
	}


	/**
	 * 获取非管理员的可用用户列表
	 * @return
	 */
	public 	List<UserEntity> listAllUser()
	{
		return userMapper.listForUser();
	}

	/**
	 * 根据部门id获取对应的用户列表
	 * @return
	 */
	@Override
	public 	List<UserEntity> getListByDepartmentId(String departmentId)
	{
		return userMapper.getListByDepartmentId(departmentId);
	}
}
